from time import sleep
import pygame
from threading import Thread
from recv_msg_thread import RecvMsgThread
from send_msg_thread import SendMsgThread
import socket
from socket import socket
import msg_router
from queue import Queue
import account

SVR_HOST = '192.168.4.53'
SVR_PORT = 65500

max_robot_id = 1

class Player(Thread):
    screen:pygame.Surface
    recv_msg_thread:RecvMsgThread
    send_msg_thread:SendMsgThread
    data:dict
    sock_msg_queue:Queue

    def __init__(self, screen, sock_msg_queue):
        super().__init__()
        self.screen = screen
        self.sock_msg_queue = sock_msg_queue
        self.data = {}

    def connect_svr(self):
        sock = socket()
        sock.connect((SVR_HOST, SVR_PORT))
        self.sock = sock

    def send_msg(self, msg_id, msg):
        if self.send_msg_thread:
            self.send_msg_thread.send_msg(msg_id, msg)

    def run(self):
        self.connect_svr()
        # 连接完成创建 RecvMsgThread和SendMsgThread
        self.recv_msg_thread = RecvMsgThread(self.sock, self.sock_msg_queue)
        self.recv_msg_thread.start()
        self.send_msg_thread = SendMsgThread(self.sock)
        self.send_msg_thread.start()
        running = True
        sleep(1)
        global max_robot_id
        account_name = "robot_" + str(max_robot_id)
        max_robot_id += 1
        account.tos_login(self, account_name)

        while(running):
            msg_id, msg = self.sock_msg_queue.get()
            msg_router.router(self, msg_id, msg)
            


# 创建一个新的玩家
def new_player(screen):
    sock_msg_queue = Queue()
    return Player(screen, sock_msg_queue)



